package com.baizhi.lqy.service;

import com.baizhi.lqy.dao.AdminDao;
import com.baizhi.lqy.entity.Admin;
import com.baizhi.lqy.utils.ImageCodeUtil;
import com.baizhi.lqy.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class AdminServiceImpl implements AdminService{

    @Autowired
    private AdminDao adminDao;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    //注册
    public void insertService(Admin admin) {
        //原密码
        String password = admin.getPassword();

        //加随机盐
        String salt = Md5Utils.getSalt(6);
        String saltPwd = salt+password+salt;

        //MD5加密之后
        String md5Code = Md5Utils.getMd5Code(saltPwd);

        //修改密码和随机盐
        admin.setSalt(salt);
        admin.setPassword(md5Code);

        adminDao.insert(admin);
    }

    //验证码
    public Map<String,String > getimage() throws IOException {
        Map<String,String> map = new HashMap<>();
        //调用工具类，获取随机验证码
        String code = ImageCodeUtil.getSecurityCode();
        //调用工具类，根据随机码生成图片base64
        String imgBase64 = ImageCodeUtil.careateImgBase64(code);
        //把base64的图片信息存入map集合
        map.put("imgCode",imgBase64);
        //获取UUID
        String uuid = UUID.randomUUID().toString();
        //将UUID存入map
        map.put("token",uuid);
        //往Redis中存验证码
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("CODE_"+uuid,code,1, TimeUnit.MINUTES);

        return map;
    }

    //登录
    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public Admin queryOne(String name) {
        return adminDao.selectOne(name);
    }

    //登录检查
    public Map<String, String> login(@RequestBody Admin admin,String token){
        Map<String, String> map = new HashMap<>();

        //从Redis上获取验证码
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object o = valueOperations.get("CODE_" + token);

        //检查验证码
        if(o == null){  //验证码过期
            map.put("message","验证码已过期");
            map.put("state","error");
            return map;
        }
        String serverCode = o.toString();
        if(!admin.getEnCode().equals(serverCode)){  //验证码错误
            map.put("message","验证码错误");
            map.put("state","error");
            return map;
        }

        //验证码正确，检查账号密码
        Admin user = adminDao.selectOne(admin.getUsername());
            if(user == null){
                map.put("message","账号不存在");
                map.put("state","error");
                return map;
            }else {
                if(admin.getSalt() == "0"){
                    map.put("message","账号已冻结");
                    map.put("state","error");
                    return map;
                }
                //获取输入的密码
                String password = admin.getPassword();
                //加随机盐
                String pas = user.getSalt()+password+user.getSalt();
                //进行MD5加密
                String md5Pwd = Md5Utils.getMd5Code(pas);
                if(md5Pwd.equals(user.getPassword())){  //账号密码正确
                    map.put("state","success");
                    map.put("message",token);
                    valueOperations.set("TOKEN_"+token,user);
                }else {
                    map.put("message","密码错误");
                    map.put("state","error");
                    return map;
                }
            }
        return map;
    }

    //获取用户登录信息
    public Admin getUserInfo(String token){
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        ValueOperations valueOperations = redisTemplate.opsForValue();

        return (Admin) valueOperations.get("TOKEN_" + token);
    }

    //退出登录
    public void logOut(String token){
        //从Redis中删除登录
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.delete("TOKEN_" + token);
    }

}
